<template>
  <div class="users-container">
    <a-card>
      <template #title>用户管理</template>
      <template #extra>
        <a-space>
          <a-button type="primary" @click="handleExport">
            <template #icon><DownloadOutlined /></template>
            导出
          </a-button>
          <a-button type="primary" @click="handleAdd">
            <template #icon><PlusOutlined /></template>
            添加用户
          </a-button>
        </a-space>
      </template>

      <a-form layout="inline" class="search-form">
        <a-form-item label="姓名" class="search-form-item">
          <a-input
            v-model:value="searchForm.name"
            placeholder="请输入姓名"
            allow-clear
            @pressEnter="handleSearch"
          />
        </a-form-item>
        <a-form-item label="手机号" class="search-form-item">
          <a-input
            v-model:value="searchForm.phone"
            placeholder="请输入手机号"
            allow-clear
            @pressEnter="handleSearch"
          />
        </a-form-item>
        <a-form-item label="产品类别" class="search-form-item">
          <a-select
            v-model:value="searchForm.productCategory"
            placeholder="请选择产品类别"
            :options="productCategoryOptions"
            allow-clear
          />
        </a-form-item>
        <a-form-item class="search-form-item">
          <a-button type="primary" @click="handleSearch">
            <template #icon><SearchOutlined /></template>
            搜索
          </a-button>
          <a-button style="margin-left: 8px" @click="handleReset">
            <template #icon><ReloadOutlined /></template>
            重置
          </a-button>
        </a-form-item>
      </a-form>

      <a-table
        :columns="columns"
        :data-source="users"
        :loading="loading"
        :pagination="pagination"
        @change="handleTableChange"
        row-key="id"
      >
        <template #bodyCell="{ column, record }">
          <template v-if="column.key === 'action'">
            <a-space>
              <a @click="handleEdit(record)">编辑</a>
              <a-divider type="vertical" />
              <a-popconfirm
                title="确定要删除该用户吗？"
                ok-text="确定"
                cancel-text="取消"
                @confirm="handleDelete(record)"
              >
                <a class="danger-link">删除</a>
              </a-popconfirm>
            </a-space>
          </template>
        </template>
      </a-table>
    </a-card>

    <a-modal
      v-model:visible="dialogVisible"
      :title="dialogType === 'add' ? '添加用户' : '编辑用户'"
      @ok="handleDialogConfirm"
      :confirm-loading="dialogLoading"
      :maskClosable="false"
      width="600px"
    >
      <a-form
        ref="formRef"
        :model="form"
        :rules="rules"
        :label-col="{ span: 6 }"
        :wrapper-col="{ span: 16 }"
        layout="horizontal"
      >
        <a-form-item label="姓名" name="name">
          <a-input v-model:value="form.name" placeholder="请输入姓名" />
        </a-form-item>
        <a-form-item label="公司名称" name="companyName">
          <a-input v-model:value="form.companyName" placeholder="请输入公司名称" />
        </a-form-item>
        <a-form-item label="职位" name="position">
          <a-input v-model:value="form.position" placeholder="请输入职位" />
        </a-form-item>
        <a-form-item label="手机号" name="phone">
          <a-input v-model:value="form.phone" placeholder="请输入手机号" />
        </a-form-item>
        <a-form-item label="邮箱" name="email">
          <a-input v-model:value="form.email" placeholder="请输入邮箱" />
        </a-form-item>
        <a-form-item label="产品类别" name="productCategory">
          <a-select
            v-model:value="form.productCategory"
            placeholder="请选择产品类别"
            :options="productCategoryOptions"
          />
        </a-form-item>
      </a-form>
    </a-modal>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue'
import { message } from 'ant-design-vue'
import { PlusOutlined, SearchOutlined, ReloadOutlined, DownloadOutlined } from '@ant-design/icons-vue'
import type { TablePaginationConfig } from 'ant-design-vue'
import { userApi, type User } from '../api/user'

interface SearchForm {
  name: string
  phone: string
  productCategory: string
}

interface Form {
  id?: number
  name: string
  companyName: string
  position: string
  phone: string
  email: string
  productCategory: string
}

const columns = [
  {
    title: '姓名',
    dataIndex: 'name',
    key: 'name'
  },
  {
    title: '公司名称',
    dataIndex: 'companyName',
    key: 'companyName'
  },
  {
    title: '职位',
    dataIndex: 'position',
    key: 'position'
  },
  {
    title: '手机号',
    dataIndex: 'phone',
    key: 'phone'
  },
  {
    title: '邮箱',
    dataIndex: 'email',
    key: 'email'
  },
  {
    title: '产品类别',
    dataIndex: 'productCategory',
    key: 'productCategory'
  },
  {
    title: '创建时间',
    dataIndex: 'createTime',
    key: 'createTime'
  },
  {
    title: '操作',
    key: 'action',
    width: 150,
    fixed: 'right'
  }
]

const users = ref<User[]>([])
const loading = ref(false)
const dialogVisible = ref(false)
const dialogType = ref<'add' | 'edit'>('add')
const dialogLoading = ref(false)
const formRef = ref()

const pagination = reactive({
  current: 1,
  pageSize: 10,
  total: 0,
  showSizeChanger: true,
  showQuickJumper: true,
  showTotal: (total: number) => `共 ${total} 条`
})

const searchForm = reactive<SearchForm>({
  name: '',
  phone: '',
  productCategory: ''
})

const productCategoryOptions = [
  { label: '请选择', value: '' },
  { label: '医疗器械', value: '医疗器械' },
  { label: '农药', value: '农药' },
  { label: '医药', value: '医药' },
  { label: '化学品', value: '化学品' },
  { label: '化妆品', value: '化妆品' },
  { label: '危化品', value: '危化品' },
  { label: '其他', value: '其他' }
]

const form = reactive<Form>({
  name: '',
  companyName: '',
  position: '',
  phone: '',
  email: '',
  productCategory: ''
})

const rules = {
  name: [
    { required: true, message: '请输入姓名' }
  ],
  companyName: [
    { required: true, message: '请输入公司名称' }
  ],
  position: [
    { required: true, message: '请输入职位' }
  ],
  phone: [
    { required: true, message: '请输入手机号' },
    { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号' }
  ],
  email: [
    { type: 'email', message: '请输入正确的邮箱地址' }
  ],
  productCategory: [
    { required: true, message: '请选择产品类别' }
  ]
}

const loadUsers = async () => {
  loading.value = true
  try {
    const res = await userApi.getList({
      current: pagination.current || 1,
      size: pagination.pageSize || 10,
      name: searchForm.name,
      phone: searchForm.phone,
      productCategory: searchForm.productCategory
    })
    users.value = res.data.records
    pagination.total = res.data.total
  } catch (error) {
    message.error('获取用户列表失败')
  } finally {
    loading.value = false
  }
}

const handleSearch = () => {
  pagination.current = 1
  loadUsers()
}

const handleReset = () => {
  searchForm.name = ''
  searchForm.phone = ''
  searchForm.productCategory = ''
  pagination.current = 1
  loadUsers()
}

const handleTableChange = (pag: TablePaginationConfig) => {
  if (pag.current) pagination.current = pag.current
  if (pag.pageSize) pagination.pageSize = pag.pageSize
  loadUsers()
}

const resetForm = () => {
  form.id = undefined
  form.name = ''
  form.companyName = ''
  form.position = ''
  form.phone = ''
  form.email = ''
  form.productCategory = ''
}

const handleAdd = () => {
  dialogType.value = 'add'
  resetForm()
  dialogVisible.value = true
}

const handleEdit = (record: User) => {
  dialogType.value = 'edit'
  form.id = record.id
  form.name = record.name
  form.companyName = record.companyName
  form.position = record.position
  form.phone = record.phone
  form.email = record.email
  form.productCategory = record.productCategory
  dialogVisible.value = true
}

const handleDelete = async (record: User) => {
  try {
    await userApi.delete(record.id!)
    message.success('删除成功')
    loadUsers()
  } catch (error) {
    message.error('删除失败')
  }
}

const handleDialogConfirm = async () => {
  try {
    await formRef.value.validate()
    dialogLoading.value = true
    
    if (dialogType.value === 'add') {
      await userApi.submit(form)
      message.success('添加成功')
    } else {
      await userApi.update(form.id!, form)
      message.success('更新成功')
    }
    
    dialogVisible.value = false
    loadUsers()
  } catch (error) {
    if (error instanceof Error) {
      message.error(error.message)
    }
  } finally {
    dialogLoading.value = false
  }
}

const handleExport = async () => {
  try {
    const response = await userApi.export()
    // 创建下载链接
    const blob = new Blob([response.data], { type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' })
    const url = window.URL.createObjectURL(blob)
    const link = document.createElement('a')
    link.href = url
    link.download = '用户列表.xlsx'
    document.body.appendChild(link)
    link.click()
    document.body.removeChild(link)
    window.URL.revokeObjectURL(url)
    message.success('导出成功')
  } catch (error) {
    console.error('导出失败:', error)
    message.error('导出失败')
  }
}

onMounted(() => {
  loadUsers()
})
</script>

<style scoped>
.users-container {
  padding: 24px;
  height: 100%;
  display: flex;
  flex-direction: column;
}

.search-form {
  margin-bottom: 24px;
}

.search-form-item {
  flex-shrink: 0;
}

.search-form-item :deep(.ant-input),
.search-form-item :deep(.ant-select) {
  width: 140px !important;
}

.search-form-item:last-child {
  margin-left: auto;
}

.search-form-item:last-child :deep(.ant-btn) {
  flex-shrink: 0;
}

.danger-link {
  color: #ff4d4f;
}

.danger-link:hover {
  color: #ff7875;
}

:deep(.ant-form-item) {
  margin-bottom: 16px;
}

:deep(.ant-modal-body) {
  padding: 24px;
}

:deep(.ant-card) {
  height: 100%;
  display: flex;
  flex-direction: column;
}

:deep(.ant-card-body) {
  flex: 1;
  overflow: hidden;
  display: flex;
  flex-direction: column;
}

:deep(.ant-table-wrapper) {
  flex: 1;
  overflow: hidden;
}

:deep(.ant-table) {
  height: 100%;
}

:deep(.ant-table-container) {
  height: 100%;
}

:deep(.ant-table-body) {
  height: calc(100% - 39px) !important;
  overflow-y: auto !important;
}
</style> 